package org.workstream.timer;

import java.util.TimerTask;

public abstract class SuperTimerTask extends TimerTask {
	private boolean isInRunning;
	private Object run_mutex;
	private boolean isStopTask;
	private Object stop_mutex;
	public SuperTimerTask(){
		super();
		isInRunning = false;
		run_mutex = new Object();
		isStopTask = false;
		stop_mutex = new Object();
	}
	private void setISInRunning(boolean b){
		synchronized(run_mutex){
			isInRunning = b;
		}
	}
	public boolean getISInRunning(){
		synchronized(run_mutex){
			return isInRunning;
		}
	}
	public void setIsStopTask(){
		synchronized(stop_mutex){
			isStopTask = true;
		}
	}
	protected boolean getIsStopTask(){
		synchronized(stop_mutex){
			return isStopTask;
		}
	}
	@Override
	final public void run() {
		// TODO Auto-generated method stub
		if(getIsStopTask())
			return;
		setISInRunning(true);
		taskEntity();
		setISInRunning(false);
	}
	protected abstract void taskEntity();
	public void closeAndWaitTask(){
		setIsStopTask();
		while(getISInRunning())
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {}
	}
}
